package com.java.basis.thread.cas.atomic;

import org.springframework.security.core.parameters.P;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;

/**
 * @author wangning
 * @create 2022-01-28 15:03
 */
public class TestAtomicInteger01 {
	public static void main(String[] args) {
		AtomicInteger i = new AtomicInteger(0);
//		i.compareAndSet(0, 1);
		System.out.println(i.incrementAndGet());//++i
		System.out.println(i.getAndIncrement());//i++
		System.out.println(i.get());
		i.decrementAndGet();
		i.getAndDecrement();
		i.getAndAdd(5);
		System.out.println(i.get());

		//接收的是接口类型，支持lambda，读取到 设置
		i.updateAndGet(x -> x * 10);
		System.out.println(i.get());

		while (true) {
			int prev = i.get();
			int next = prev * 10;
			if (i.compareAndSet(prev, next)) {
				break;
			}
		}
		System.out.println(i.get());

		int aa = updateAndSet(i, p -> p * 10);
		System.out.println(aa);

	}

	public static int updateAndSet(AtomicInteger i, IntUnaryOperator operator) {
		while (true) {
			int prev = i.get();
			int next = operator.applyAsInt(prev);
			if (i.compareAndSet(prev, next)) {
				return next;
			}
		}
	}
}
